!
! prvni, uspesny pokus vetveni s omezenimi, neprohledava vsechny
! permutace, ale jen ty nadejne a vyporada se i s chybejicimi 
! hvezdami, zatim neni schopen rozume ztotoznit v pripade, ze 
! si neodpovidaji prvni hevzdy.
!

module modzkus

  integer, parameter :: n = 10
  integer :: nvolani = 0
  integer :: a(n),b(n)
  logical :: volna(n)
  real :: x1(n), x2(n)

contains

recursive subroutine zkus(i)

  integer :: i,j,l,k
  real :: s,d,dd,ns
  logical :: nalezena

  nvolani = nvolani + 1
 ! write(*,*) i,":",volna,nvolani

  nalezena = .false.
  do j = 1, n
     do k =1,n
        dd = abs((x2(j) - x2(k)) -  (x1(i) - x1(1)))
        !    write(*,*) i,j,k,dd,a
 
        if( volna(j) .and. dd < 0.1 )then
           nalezena = .true.
           a(i) = j
           b(j) = i
           volna(j) = .false.
           if( i < n )then
              call zkus(i+1)
           endif
           ns = count(mask= .not. volna)
           d = sum(x2 - x1(b),mask=.not.volna)/ns
           !                d = sum(x2(a) - x1,mask=.not.volna)/ns
           !                 s = sum((x2(a) - (x1 + d))**2,mask= .not. volna)
           where( volna )
             b = 0
           end where
           s = sum((x2 - (x1(b) + d))**2,mask=b>0)
           if( s < 1.0 ) write(*,*) (l,l=1,n)," -> ",a," :",s,d,ns,dd,volna,b
           volna(j) = .true.
        endif
     enddo
enddo

if( .not. nalezena ) then
           if( i < n )then
              call zkus(i+1)
           endif
endif

end subroutine zkus

end module modzkus


program zk

use modzkus

  x1 = (/ 0, 10, 20, 50, 40, 110, 120, 130, 140, 150 /)
  x2 = (/20, 30, 10, -60, 50, 120, 130, 140, 150, 160 /)
  a = 0
  b = 0

  volna = .true.

  call zkus(1)

  write(*,*) "pocet volani=",nvolani

end program zk

